/**********************************************************************
 * FILE : WebAgent.java
 * CREATE DATE : 2011-12-12
 * DESCRIPTION :
 *		
 *      
 * CHANGE HISTORY LOG
 *---------------------------------------------------------------------
 * NO.|    DATE    |     NAME     |     REASON     | DESCRIPTION
 *---------------------------------------------------------------------
 * 1  | 2011-12-12 |  Sting  |    草创版本
 *---------------------------------------------------------------------              
 **********************************************************************
 */
package com.sgm.de.benchmark;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Sting
 * TODO 主要作用:
 *		注意事项:
 */
public class WebAgent {
    private static final Logger logger = LoggerFactory.getLogger(WebAgent.class);
    static String JAVAW = "java";
    String agentIP = null;
    static int agentPort = 8887;
    static List<String> list = new ArrayList<String>();
    public static volatile boolean isStop = false;

    public WebAgent() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                ServerSocket ss;
                try {
                    ss = new ServerSocket(agentPort);
                    agentIP = ss.getInetAddress().getHostAddress();

                    while (!isStop) {
                        Socket s = ss.accept();
                        synchronized (list) {
                            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                            String line = br.readLine();
                            if (line != null) {
                                list.add(line);
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    agentPort++;
                    this.run();
                }

            }
        }).start();
    }

    public static int startProcess() {
        ProcessBuilder build = new ProcessBuilder();
        List<String> command = new ArrayList<String>();
        command.add(JAVAW);
        command.add("-classpath");
        command.add(System.getProperty("java.class.path"));
        command.add("com.sgm.de.benchmark.JMSProcesser");
        command.add(String.valueOf(agentPort));
        build.command(command);
        build.redirectErrorStream(true);
        logger.info(build.command().toString());
        Process p = null;
        final int currentPosition;
        try {
            synchronized (list) {
                currentPosition = list.size();
            }
            p = build.start();
            final BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String line = null;
                    try {
                        while ((line = br.readLine()) != null) {
                            logger.error("[P" + (currentPosition + 1) + "]" + line);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            while (list.size() == currentPosition) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    continue;
                }
            }
            String addr = list.get(currentPosition);
            return Integer.parseInt(addr.split(":")[1]);
        } catch (IOException e) {
            throw new RuntimeException("IO Exception:" + e.getMessage());
        }
    }

    /**
     * TODO 新建方法
     */
    public void stop() {
        isStop = true;
    }
}
